<?php

namespace App\Models\Traits;

use Illuminate\Support\Facades\Auth;

/**
 * 根据角色及其所属学校对数据的可管理性进行查询限制。
 */
trait HasManagable
{
    /**
     * 添加当前用户对于学校数据的可管理性查询。
     *
     * @param  \Illuminate\Database\Eloquent\Builder $query
     * @param  string $school_column    学校ID字段名
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function addManagableFilter($query, $status_column = 'check_state', $user_column = 'create_by')
    {
        $me = Auth::user(); /** @var User $me */
        if ( $me->hasRole([2])) {
            $query->where(function ($q) {
                $q->where('activity_info.creator_id', Auth::id());
            })->orWhere(function ($q) use ($me) {
//                $q->instance()->where('status', '!=','REVIEWED');
                $q->where('p.user_id', $me->id);
                $q->where('b.status', '!=', 'FILL_IN');
            });
        }else{
            $query->whereHas('instance', function ($query) {
                $query->where('status', '!=','FILL_IN')
                    ->orWhere('activity_info.creator_id', Auth::id());
            });
        }
        return $query;
    }
}
